package com.zzyl.nursing.task;

import com.zzyl.nursing.service.IContractService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.zzyl.nursing.domain.Contract;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wsc
 */
@Component("contractTask")
public class ContractTask {
    @Autowired
    private IContractService contractService;

    /**
     * 定时处理合同的状态
     */
    //每天的8 16 00执行一次
    //@Scheduled(cron = "0 0 8,16 * * ?")

    public void contractStatusTask() {
        LocalDate now = LocalDate.now();

        List<Contract> list = contractService.lambdaQuery()
                .eq(Contract::getStatus, 0)
                .list();
        if (list != null && !list.isEmpty()) {
            list = list.stream()
                    .filter(contract -> contract.getStartDate().isBefore(now.atStartOfDay()))
                    .collect(Collectors.toList());
            list.forEach(contract -> contract.setStatus(1));
            if (!list.isEmpty()) {
                contractService.updateBatchById(list);
            }

        }

        List<Contract> listRun = contractService.lambdaQuery()
                .eq(Contract::getStatus, 1)
                .list();
        if (listRun != null && !listRun.isEmpty()) {
            listRun = listRun.stream()
                    .filter(contract -> contract.getEndDate().isAfter(now.atStartOfDay()))
                    .collect(Collectors.toList());
            listRun.forEach(contract -> contract.setStatus(2));
            if (!listRun.isEmpty()) {
                contractService.updateBatchById(listRun);
            }
        }

        System.out.println("开始处理合同状态" + LocalDateTime.now());
    }
}
